import { Injectable } from '@angular/core'
import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { Observable, throwError, of } from 'rxjs'
import { map, catchError } from 'rxjs/operators'

import { COMB_URL } from 'app/utils/contraints'
import { IBizUniqueness } from '@shared/interfaces/biz'

@Injectable({
  providedIn: 'root',
})
export class BusinessService {
  constructor(private http: HttpClient) {}

  // returns true means that there is no uniqueness conflict
  // returns false mean that there is a uniqueness conflict
  checkUniqueness(params: IBizUniqueness): Observable<boolean> {
    const str = Object.keys(params)
      .filter(key => params[key] !== '')
      .map(key => `${key}=${params[key]}`)
      .join('&')
    const url = `${COMB_URL}/camel/biz/uniqueness?${str}`
    return this.http
      .post<any>(
        url,
        {},
        {
          observe: 'response',
        },
      )
      .pipe(
        catchError(err => {
          if (err instanceof HttpErrorResponse) {
            return of(err)
          }

          return throwError(err)
        }),
        map(res => {
          switch (res.status) {
            case 204:
              return true
            case 409:
              return false
            default:
              throwError(res.statusText)
          }
        }),
      )
  }
}
